package com.example.demo.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池工具类
 * 用于监控和管理线程池状态
 * 
 * @author zhang
 * @date 2024
 */
public class ThreadPoolUtil {

    private static final Logger logger = LoggerFactory.getLogger(ThreadPoolUtil.class);

    /**
     * 打印线程池状态信息
     * 
     * @param poolName 线程池名称
     * @param executor 线程池
     */
    public static void printThreadPoolStatus(String poolName, ThreadPoolTaskExecutor executor) {
        ThreadPoolExecutor threadPool = executor.getThreadPoolExecutor();
        
        logger.info("========= {} 线程池状态 =========", poolName);
        logger.info("核心线程数: {}", threadPool.getCorePoolSize());
        logger.info("最大线程数: {}", threadPool.getMaximumPoolSize());
        logger.info("当前活跃线程数: {}", threadPool.getActiveCount());
        logger.info("当前线程数: {}", threadPool.getPoolSize());
        logger.info("已完成任务数: {}", threadPool.getCompletedTaskCount());
        logger.info("总任务数: {}", threadPool.getTaskCount());
        logger.info("队列大小: {}", threadPool.getQueue().size());
        logger.info("=======================================");
    }

    /**
     * 检查线程池是否健康
     * 
     * @param poolName 线程池名称
     * @param executor 线程池
     * @return boolean
     */
    public static boolean isThreadPoolHealthy(String poolName, ThreadPoolTaskExecutor executor) {
        ThreadPoolExecutor threadPool = executor.getThreadPoolExecutor();
        
        long taskCount = threadPool.getTaskCount();
        long completedTaskCount = threadPool.getCompletedTaskCount();
        int activeCount = threadPool.getActiveCount();
        int queueSize = threadPool.getQueue().size();
        int poolSize = threadPool.getPoolSize();
        int maximumPoolSize = threadPool.getMaximumPoolSize();
        
        // 检查条件
        boolean isHealthy = activeCount <= maximumPoolSize 
                && queueSize < 1000 
                && completedTaskCount <= taskCount;
        
        if (!isHealthy) {
            logger.warn("线程池 {} 状态异常 - 活跃线程: {}, 队列大小: {}", 
                    poolName, activeCount, queueSize);
        }
        
        return isHealthy;
    }

    /**
     * 获取线程池使用率
     * 
     * @param executor 线程池
     * @return double 使用率（0-1）
     */
    public static double getThreadPoolUsage(ThreadPoolTaskExecutor executor) {
        ThreadPoolExecutor threadPool = executor.getThreadPoolExecutor();
        
        int maxPoolSize = threadPool.getMaximumPoolSize();
        int activeCount = threadPool.getActiveCount();
        
        if (maxPoolSize == 0) {
            return 0.0;
        }
        
        return (double) activeCount / maxPoolSize;
    }

    /**
     * 获取线程池任务执行统计信息
     * 
     * @param poolName 线程池名称
     * @param executor 线程池
     */
    public static void printStatistics(String poolName, ThreadPoolTaskExecutor executor) {
        ThreadPoolExecutor threadPool = executor.getThreadPoolExecutor();
        
        long completedTaskCount = threadPool.getCompletedTaskCount();
        long taskCount = threadPool.getTaskCount();
        double successRate = taskCount > 0 ? 
                (double) completedTaskCount / taskCount * 100 : 0;
        
        logger.info("====== {} 执行统计 ======", poolName);
        logger.info("总任务数: {}", taskCount);
        logger.info("已完成: {}", completedTaskCount);
        logger.info("成功率: {:.2f}%", successRate);
        logger.info("=========================");
    }
}

